package com.ikingtech.platform.service.push.websocket.interceptor;

import com.ikingtech.framework.sdk.utils.Tools;
import lombok.NonNull;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * @author tie yan
 */
public class WebsocketInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(@NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response, @NonNull WebSocketHandler wsHandler, @NonNull Map<String, Object> attributes) {
        if (Tools.Str.isNotBlank(((ServletServerHttpRequest) request).getServletRequest().getParameter("userId"))) {
            attributes.put("userId", ((ServletServerHttpRequest) request).getServletRequest().getParameter("userId"));
        }
        return true;
    }

    @Override
    public void afterHandshake(@NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response, @NonNull WebSocketHandler wsHandler, Exception exception) {
        // method is empty
    }
}
